<template>
  <div class="warning-page">
    <h1>天气预警管理</h1>
    
    <!-- 未登录提示 -->
    <div v-if="!userStore.isAuthenticated" class="warning-login-tip">
      <div class="alert alert-warning">
        <i class="bi bi-exclamation-triangle-fill"></i>
        请先登录以使用预警功能
        <button class="btn btn-sm btn-primary ms-3" @click="navigateToLogin">
          前往登录
        </button>
      </div>
    </div>
    
    <!-- 已登录内容 -->
    <div v-else>
      <!-- 功能描述 -->
      <div class="description mb-4">
        <p>
          设置预警通知，当到达指定时间或倒计时结束时，系统将通过邮件发送所选城市的最新预警信息。
        </p>
      </div>
      
      <!-- 控制按钮 -->
      <div class="actions mb-4">
        <button class="btn btn-primary me-2" @click="showCreateWarningForm">
          <i class="bi bi-plus-circle"></i> 创建预警
        </button>
        <button class="btn btn-outline-primary me-2" @click="sendTestEmail">
          <i class="bi bi-envelope"></i> 发送测试邮件
        </button>
      </div>
      
      <!-- 创建预警表单 -->
      <div v-if="showForm" class="warning-form card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h5 class="m-0">{{ isEditing ? '编辑预警' : '创建预警' }}</h5>
          <button class="btn btn-sm btn-outline-secondary" @click="cancelForm">
            <i class="bi bi-x-lg"></i>
          </button>
        </div>
        <div class="card-body">
          <form @submit.prevent="submitWarningForm">
            <!-- 地点选择 -->
            <div class="mb-3">
              <label for="location" class="form-label">地点</label>
              <div class="input-group">
                <input
                  type="text"
                  class="form-control"
                  id="location"
                  v-model="searchText"
                  placeholder="搜索城市..."
                  @input="searchCity"
                  @focus="showCityResults = true"
                />
                <button 
                  v-if="searchText" 
                  class="btn btn-outline-secondary" 
                  type="button"
                  @click="clearSearch"
                >
                  <i class="bi bi-x"></i>
                </button>
              </div>
              
              <!-- 城市搜索结果 -->
              <div class="city-search-results" v-if="showCityResults && cities.length > 0">
                <div 
                  v-for="city in cities" 
                  :key="city.id" 
                  class="city-item"
                  @click="selectCity(city)"
                >
                  {{ city.name }}, {{ city.adm1 }}
                </div>
              </div>
              
              <!-- 已选地点显示 -->
              <div v-if="warningForm.location" class="selected-location mt-2">
                <span class="badge bg-info">
                  {{ warningForm.locationName }}
                  <i class="bi bi-x-circle ms-1" @click="clearSelectedCity"></i>
                </span>
              </div>
            </div>
            
            <!-- 通知方式选择 -->
            <div class="mb-3">
              <label class="form-label d-block">通知方式</label>
              <div class="form-check form-check-inline">
                <input
                  class="form-check-input"
                  type="radio"
                  id="scheduleType1"
                  value="datetime"
                  v-model="scheduleType"
                  name="scheduleType"
                />
                <label class="form-check-label" for="scheduleType1">定时发送</label>
              </div>
              <div class="form-check form-check-inline">
                <input
                  class="form-check-input"
                  type="radio"
                  id="scheduleType2"
                  value="countdown"
                  v-model="scheduleType"
                  name="scheduleType"
                />
                <label class="form-check-label" for="scheduleType2">倒计时发送</label>
              </div>
            </div>
            
            <!-- 定时发送选项 -->
            <div class="mb-3" v-if="scheduleType === 'datetime'">
              <label for="triggerTime" class="form-label">发送时间</label>
              <input
                type="datetime-local"
                class="form-control"
                id="triggerTime"
                v-model="warningForm.triggerTime"
                :min="minDateTime"
              />
            </div>
            
            <!-- 倒计时选项 -->
            <div class="mb-3" v-if="scheduleType === 'countdown'">
              <label for="countdownMinutes" class="form-label">倒计时（分钟）</label>
              <input
                type="number"
                class="form-control"
                id="countdownMinutes"
                v-model.number="warningForm.countdownMinutes"
                min="1"
                max="10080"
              />
              <div class="form-text" v-if="warningForm.countdownMinutes">
                将在 {{ formatCountdown(warningForm.countdownMinutes) }} 后发送
              </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="d-grid gap-2">
              <button type="submit" class="btn btn-primary" :disabled="!isFormValid || loading">
                <span v-if="loading" class="spinner-border spinner-border-sm me-1" role="status"></span>
                {{ isEditing ? '更新预警' : '创建预警' }}
              </button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 预警列表 -->
      <div class="warnings-list card">
        <div class="card-header">
          <h5 class="m-0">预警列表</h5>
        </div>
        <div class="card-body p-0">
          <div v-if="loading" class="text-center p-4">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
          </div>
          
          <div v-else-if="warnings.length === 0" class="text-center p-4">
            <p class="text-muted">暂无预警设置</p>
          </div>
          
          <div v-else class="list-group list-group-flush">
            <div v-for="warning in warnings" :key="warning.id" class="list-group-item">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <h5 class="mb-1">{{ warning.locationName }}</h5>
                  <p class="mb-1">
                    <span class="badge" :class="warning.isActive ? 'bg-success' : 'bg-secondary'">
                      {{ warning.isActive ? '已激活' : '已停用' }}
                    </span>
                    <span class="ms-2 text-muted">
                      <i class="bi bi-clock"></i>
                      {{ warning.isCountdown 
                        ? `倒计时: ${warning.countdownMinutes} 分钟` 
                        : `定时: ${formatDate(warning.triggerTime)}` }}
                    </span>
                  </p>
                  <small class="text-muted">
                    创建于: {{ formatDate(warning.createdAt) }}
                    <span v-if="warning.lastSentAt">
                      | 上次发送: {{ formatDate(warning.lastSentAt) }}
                    </span>
                  </small>
                </div>
                <div>
                  <button 
                    class="btn btn-sm btn-outline-primary me-1" 
                    @click="editWarning(warning)"
                  >
                    <i class="bi bi-pencil"></i>
                  </button>
                  <button 
                    class="btn btn-sm btn-outline-danger" 
                    @click="confirmDeleteWarning(warning)"
                  >
                    <i class="bi bi-trash"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认删除弹窗 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" ref="deleteModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">确认删除</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p>确定要删除对 <strong>{{ warningToDelete?.locationName }}</strong> 的预警设置吗？</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-danger" @click="deleteWarning">确认删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { warningApi, weatherApi } from '../api'
import { Modal } from 'bootstrap'

// 路由和状态
const router = useRouter()
const userStore = useUserStore()

// 数据
const warnings = ref([])
const loading = ref(false)
const showForm = ref(false)
const isEditing = ref(false)
const currentWarningId = ref(null)
const warningToDelete = ref(null)
const deleteModal = ref(null)

// 表单数据
const scheduleType = ref('datetime')
const warningForm = ref({
  location: '',
  locationName: '',
  triggerTime: '',
  isCountdown: false,
  countdownMinutes: 30
})

// 城市搜索
const searchText = ref('')
const cities = ref([])
const showCityResults = ref(false)

// 计算属性
const isFormValid = computed(() => {
  if (!warningForm.value.location || !warningForm.value.locationName) {
    return false
  }
  
  if (scheduleType.value === 'datetime' && !warningForm.value.triggerTime) {
    return false
  }
  
  if (scheduleType.value === 'countdown' && 
      (!warningForm.value.countdownMinutes || warningForm.value.countdownMinutes <= 0)) {
    return false
  }
  
  return true
})

const minDateTime = computed(() => {
  const now = new Date()
  now.setMinutes(now.getMinutes() + 1)
  return now.toISOString().slice(0, 16)
})

// 初始化
onMounted(async () => {
  // 初始化用户状态
  if (!userStore.user) {
    userStore.initUser()
  }
  
  // 给用户状态初始化一些时间
  setTimeout(async () => {
    // 加载用户的预警设置
    if (userStore.isAuthenticated) {
      loadWarnings()
    }
    
    // 初始化删除确认弹窗
    deleteModal.value = new Modal(document.getElementById('deleteModal'))
  }, 500)
  
  // 点击外部时隐藏城市搜索结果
  document.addEventListener('click', (e) => {
    const citySearchResults = document.querySelector('.city-search-results')
    const citySearchInput = document.getElementById('location')
    
    if (citySearchResults && citySearchInput && 
        !citySearchResults.contains(e.target) && 
        !citySearchInput.contains(e.target)) {
      showCityResults.value = false
    }
  })
})

// 方法
async function loadWarnings() {
  try {
    loading.value = true
    const response = await warningApi.getUserWarnings()
    warnings.value = response.data.warnings
  } catch (error) {
    console.error('加载预警设置失败:', error)
  } finally {
    loading.value = false
  }
}

function navigateToLogin() {
  router.push('/login')
}

function showCreateWarningForm() {
  resetForm()
  isEditing.value = false
  showForm.value = true
}

function resetForm() {
  scheduleType.value = 'datetime'
  warningForm.value = {
    location: '',
    locationName: '',
    triggerTime: '',
    isCountdown: false,
    countdownMinutes: 30
  }
  searchText.value = ''
  cities.value = []
  currentWarningId.value = null
}

function cancelForm() {
  showForm.value = false
  resetForm()
}

async function searchCity() {
  if (!searchText.value || searchText.value.length < 2) {
    cities.value = []
    return
  }
  
  try {
    const response = await weatherApi.searchCity(searchText.value)
    cities.value = response.location || []
    showCityResults.value = true
  } catch (error) {
    console.error('城市搜索失败:', error)
  }
}

function selectCity(city) {
  warningForm.value.location = city.id
  warningForm.value.locationName = `${city.name}, ${city.adm1}`
  searchText.value = `${city.name}, ${city.adm1}`
  showCityResults.value = false
}

function clearSearch() {
  searchText.value = ''
  cities.value = []
  showCityResults.value = false
}

function clearSelectedCity() {
  warningForm.value.location = ''
  warningForm.value.locationName = ''
  searchText.value = ''
}

async function submitWarningForm() {
  if (!isFormValid.value) return
  
  try {
    loading.value = true
    
    // 准备提交数据
    const formData = {
      location: warningForm.value.location,
      locationName: warningForm.value.locationName,
      isCountdown: scheduleType.value === 'countdown',
      triggerTime: scheduleType.value === 'datetime' ? warningForm.value.triggerTime : undefined,
      countdownMinutes: scheduleType.value === 'countdown' ? warningForm.value.countdownMinutes : undefined
    }
    
    // 创建或更新预警
    if (isEditing.value && currentWarningId.value) {
      await warningApi.updateWarning(currentWarningId.value, formData)
    } else {
      await warningApi.createWarning(formData)
    }
    
    // 刷新列表并重置表单
    await loadWarnings()
    showForm.value = false
    resetForm()
  } catch (error) {
    console.error('保存预警设置失败:', error)
  } finally {
    loading.value = false
  }
}

function editWarning(warning) {
  isEditing.value = true
  currentWarningId.value = warning.id
  
  // 设置表单数据
  scheduleType.value = warning.isCountdown ? 'countdown' : 'datetime'
  warningForm.value = {
    location: warning.location,
    locationName: warning.locationName,
    triggerTime: warning.triggerTime ? new Date(warning.triggerTime).toISOString().slice(0, 16) : '',
    isCountdown: warning.isCountdown,
    countdownMinutes: warning.countdownMinutes || 30
  }
  
  searchText.value = warning.locationName
  showForm.value = true
}

function confirmDeleteWarning(warning) {
  warningToDelete.value = warning
  deleteModal.value.show()
}

async function deleteWarning() {
  if (!warningToDelete.value) return
  
  try {
    loading.value = true
    await warningApi.deleteWarning(warningToDelete.value.id)
    
    // 关闭弹窗并刷新列表
    deleteModal.value.hide()
    await loadWarnings()
  } catch (error) {
    console.error('删除预警设置失败:', error)
  } finally {
    loading.value = false
    warningToDelete.value = null
  }
}

async function sendTestEmail() {
  try {
    loading.value = true
    const response = await warningApi.sendTestEmail()
    alert('测试邮件已发送，请检查您的邮箱')
  } catch (error) {
    console.error('发送测试邮件失败:', error)
    alert('发送测试邮件失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 辅助函数
function formatDate(dateString) {
  if (!dateString) return '未设置'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function formatCountdown(minutes) {
  if (minutes < 60) {
    return `${minutes} 分钟`
  } else if (minutes < 1440) {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return `${hours} 小时 ${mins > 0 ? mins + ' 分钟' : ''}`
  } else {
    const days = Math.floor(minutes / 1440)
    const hours = Math.floor((minutes % 1440) / 60)
    return `${days} 天 ${hours > 0 ? hours + ' 小时' : ''}`
  }
}
</script>

<style scoped>
.warning-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.description {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
  border-left: 4px solid #0d6efd;
}

.warning-login-tip {
  margin: 30px 0;
}

.city-search-results {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #ced4da;
  border-radius: 0 0 5px 5px;
  z-index: 1000;
  margin-top: 2px;
}

.city-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.city-item:hover {
  background-color: #f8f9fa;
}

.selected-location {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.selected-location .badge {
  display: inline-flex;
  align-items: center;
}

.selected-location .bi-x-circle {
  cursor: pointer;
  margin-left: 5px;
}
</style> 